document.addEventListener('DOMContentLoaded', () => {
  const btn     = document.getElementById('drawButton');
  const stepsEl = document.getElementById('steps');
  const rarityEl= document.getElementById('rarity-label');
  const hintEl  = document.getElementById('hint');

  async function drawOnce() {
    const btnEl = document.getElementById('drawButton');
    const cardEl = document.getElementById('card');

    // disable button during draw
    if (btnEl) btnEl.disabled = true;
    if (rarityEl) rarityEl.textContent = '…';
    if (stepsEl) stepsEl.innerHTML = '<li>抽取中，请稍候…</li>';

    // reset any previous animation classes
    const animEl = document.getElementById('animation');
    if (animEl) {
      animEl.className = '';
      animEl.classList.add('playing');
      animEl.classList.remove('show-R','show-SR','show-SSR');
    }
    if (cardEl) {
      cardEl.classList.remove('rarity-R','rarity-SR','rarity-SSR');
    }

    try {
      const res = await fetch('/draw', { cache: 'no-store' });
      if (!res.ok) throw new Error('网络错误：' + res.status);
      const data = await res.json();

      const { rarity, tasks, anchorsPreview } = data;

      // ensure minimum placeholder duration
      const minPlaceholderMs = 800;
      const rarityRevealMs = 600;

      // wait remaining time if needed
      const t0 = Date.now();

      // reveal rarity animation after placeholder
      const reveal = async () => {
        if (animEl) {
          animEl.classList.remove('playing');
          animEl.classList.add('show-' + rarity);
        }
        if (cardEl) cardEl.classList.add('rarity-' + rarity);
        if (rarityEl) rarityEl.textContent = rarity || '—';

        // wait rarity animation time then show tasks
        await new Promise(r => setTimeout(r, rarityRevealMs));

        // render tasks
        if (stepsEl) {
          stepsEl.innerHTML = (tasks && tasks.length)
            ? tasks.map(t => `<li>${t.text}</li>`).join('')
            : '<li>没有可用的题目。</li>';
        }

        // show anchors hint
        if (hintEl) {
          hintEl.style.display = 'block';
          hintEl.textContent = `锚点预览：章节=${Object.keys(anchorsPreview.sections || {}).length}, 段落=${anchorsPreview.paragraphCount}`;
        }

        if (btnEl) btnEl.disabled = false;
      };

      const elapsed = Date.now() - t0;
      const waitMs = Math.max(0, minPlaceholderMs - elapsed);
      setTimeout(reveal, waitMs);
    } catch (err) {
      if (rarityEl) rarityEl.textContent = '—';
      if (stepsEl) stepsEl.innerHTML = `<li class="error">请求失败：${err.message}</li>`;
      const btnEl = document.getElementById('drawButton');
      if (btnEl) btnEl.disabled = false;
    }
  }

  if (btn) btn.addEventListener('click', drawOnce);
});
